package com.aurora.spider.gitee;

import com.alibaba.fastjson.JSONObject;
import com.aurora.event.GiteeSpiderEvent;
import com.aurora.util.RegrexUtil;
import com.geccocrawler.gecco.annotation.PipelineName;
import com.geccocrawler.gecco.pipeline.Pipeline;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by jackie on 18/1/15.
 */
@PipelineName("giteeProDetailPipeline")
@Component
@Slf4j
public class ProductDetailPipeline implements Pipeline<ProductDetail>, ApplicationContextAware {


    private static ApplicationContext applicationContext;

    @Override
    public void process(ProductDetail productDetail) {
        applicationContext.publishEvent(new GiteeSpiderEvent(productDetail));

    }

    private void toText(ProductDetail productDetail) {
        System.out.println("~~~~~~~~~giteeProDetailPipeline~~~~~~~~~~~" + JSONObject.toJSONString(productDetail));
        File resultFile = new File("result.txt");
        if (!resultFile.exists()) {
            try {
                resultFile.createNewFile();
            } catch (IOException e) {
                System.out.println("create result file failed: " + e);
            }
        }

        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter("result.txt", true);
        } catch (IOException e) {
            System.out.println("IOException");
        }

        try {
            fileWriter.write(RegrexUtil.match(productDetail.getGitUrl()));
//            fileWriter.write(productDetail.getContent());
            fileWriter.flush();
        } catch (IOException e) {
            System.out.println("fileWriter.write failed: " + e);
        } finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                System.out.println("fileWriter.close failed");
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;
    }
}
